package com.jvyou.app.ds.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jvyou.app.common.constants.RedisKey;
import com.jvyou.app.common.domain.dto.UserDto;
import com.jvyou.app.common.domain.entity.User;
import com.jvyou.app.common.domain.model.LoginUser;
import com.jvyou.app.common.domain.model.PageResult;
import com.jvyou.app.common.domain.model.Result;
import com.jvyou.app.common.domain.vo.UserVo;
import com.jvyou.app.common.enums.HttpCodeEnum;
import com.jvyou.app.common.utils.bean.BeanCopyUtils;
import com.jvyou.app.common.utils.orm.WrapperTool;
import com.jvyou.app.ds.mapper.MenuMapper;
import com.jvyou.app.ds.mapper.RoleMapper;
import com.jvyou.app.ds.mapper.UserMapper;
import com.jvyou.app.ds.service.UserService;
import com.jvyou.app.ds.utils.login.LoginContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 用户表(User)表服务实现类
 *
 * @author 橘柚
 * @since 2025-03-04 08:55:27
 */
@Service("userService")
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final MenuMapper menuMapper;

    private QueryWrapper<User> getWrapper(UserDto userDto) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        WrapperTool.notEmptyEq(wrapper, "username", userDto.getUsername());
        WrapperTool.notEmptyLike(wrapper, "contact_name", userDto.getContactName());
        WrapperTool.notEmptyEq(wrapper, "type", userDto.getType());
        WrapperTool.notEmptyLike(wrapper, "simplified_code", userDto.getSimplifiedCode());
        return wrapper;
    }

    @Override
    public List<UserVo> listUser(UserDto userDto) {
        List<User> userList = list(getWrapper(userDto));
        return BeanCopyUtils.copyBeanList(userList, UserVo.class);
    }

    @Override
    public PageResult<UserVo> pageUser(UserDto userDto) {
        IPage<User> page = new Page<>(userDto.getCurrent(), userDto.getPageSize());
        page = page(page, getWrapper(userDto));
        List<UserVo> userVoList = BeanCopyUtils.copyBeanList(page.getRecords(), UserVo.class);
        return PageResult.success(page.getTotal(), userVoList);
    }

    @Override
    public Result<Boolean> addUser(User user) {
        // 1. 首先判断用户名是否重复
        if (count(new QueryWrapper<User>().eq("username", user.getUsername())) > 0) {
            return Result.error(HttpCodeEnum.DATA_EXIST, "该用户名已经重复");
        }
        // 2. 判断手机号是否重复
        if (count(new QueryWrapper<User>().eq("phone", user.getPhone())) > 0) {
            return Result.error(HttpCodeEnum.DATA_EXIST, "该手机号已经绑定用户，请更换手机号重试");
        }
        // 3. 加密密码
        user.setPassword(BCrypt.hashpw("123123", BCrypt.gensalt()));
        return Result.success(save(user));
    }

    @Transactional
    @Override
    public Boolean updateUserInfo(User user) {
        Long userId = LoginContext.getUserId();
        user.setId(userId);
        // 修改用户信息
        updateById(user);
        // 更新缓存
        user = getById(userId);

        LoginUser loginUser = BeanCopyUtils.copyBean(user, LoginUser.class);
        List<String> roleList = roleMapper.getRoleByUserId(user.getId());
        List<String> permissionList = menuMapper.getPermissionByUserId(user.getId());
        loginUser.setRoles(roleList);
        loginUser.setPermissions(permissionList);
        StpUtil.getSession().set(RedisKey.LOGIN_USER_KEY + user.getId(), loginUser);
        return true;
    }
}
